import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, Modal, Form, Radio, message } from 'antd';
import React, { useState, useRef } from 'react';
import { history, connect, FormattedMessage, useIntl } from 'umi';

import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import { setRefreshTime, getRefreshTime } from '@/services';

const AvatarDropdown = (props) => {
  const intl = useIntl();
  const [formRefresh] = Form.useForm();
  const [visibleRefresh, setVisibleRefresh] = useState(false);
  const [submittingRefresh, setSubmittingRefresh] = useState(false);

  const handleCancelRefresh = () => {
    setVisibleRefresh(false);
    formRefresh.resetFields();
    setSubmittingRefresh(false);
  };

  const handleOkRefresh = async () => {
    await formRefresh.validateFields();
    let values = formRefresh.getFieldsValue();
    setSubmittingRefresh(true);
    const res = await setRefreshTime({
      value: values.warningFrequency,
      id: 2,
    });
    if (res) {
      message.success(
        intl.formatMessage({
          id: 'pages.success',
        }),
      );
      handleCancelRefresh();
    }
  };
  const onMenuClick = async (event) => {
    const { key } = event;

    if (key === 'logout') {
      const { dispatch } = props;

      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }

      return;
    }
    if (key === 'setting') {
      setVisibleRefresh(true);
      const res = await getRefreshTime(2);
      if (res) {
        formRefresh.setFields([
          {
            name: 'warningFrequency',
            value: res.data.value,
          },
        ]);
      }
    }

    // history.push(`/account/${key}`);
  };

  const {
    currentUser = {
      avatar: '',
      name: '',
    },
    menu,
  } = props;
  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      {menu && (
        <Menu.Item key="center">
          <UserOutlined />
          个人中心
        </Menu.Item>
      )}
      {menu && (
        <Menu.Item key="settings">
          <SettingOutlined />
          个人设置
        </Menu.Item>
      )}
      {menu && <Menu.Divider />}

      <Menu.Item key="setting">
        <SettingOutlined />
        设置
      </Menu.Item>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return currentUser && currentUser.name ? (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          {/* <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" /> */}
          <span className={`${styles.name} anticon`}>{currentUser.name}</span>
        </span>
      </HeaderDropdown>
      <Modal
        title={<FormattedMessage id="pages.setSaveTime" defaultMessage="设置数据留存时间" />}
        visible={visibleRefresh}
        onOk={handleOkRefresh}
        onCancel={handleCancelRefresh}
        confirmLoading={submittingRefresh}
      >
        <Form form={formRefresh} labelCol={{ span: 6 }}>
          <Form.Item
            label={<FormattedMessage id="pages.timeField" defaultMessage="选择时间" />}
            name="warningFrequency"
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'pages.p_warningFrequency' }),
              },
            ]}
          >
            <Radio.Group>
              <Radio value={'1'}>7天</Radio>
              <Radio value={'2'}>1个月</Radio>
              <Radio value={'3'}>3个月</Radio>
              {/* <Radio value={4}>1年</Radio> */}
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  ) : (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );
};

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
